package kr.hkit.androidcomplete03.ch281;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch281.common.Item;
import kr.hkit.androidcomplete03.ch281.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class PullParser extends Activity {
	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch281_parser);
		list = (ListView) findViewById(R.id.ch281_parser_listview);
		new ParsingXml().execute("order.xml");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {
		ProgressDialog progressDlg;

		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(PullParser.this, "Wait. . .",
					"order.xml Parsing. . .");
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			BufferedReader br = null;
			try {
				//웹의 xml을 읽어오고 싶으면 openFileInput이 아니라 웹 문서를 읽어오면됨
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return ParsingXml(sb.toString());
		}// end of method doInBackground()

		private ArrayList<Item> ParsingXml(String xml) {
			final String TAG = "XML PULL PARSER";
			ArrayList<Item> arLists = new ArrayList<Item>();
			Item item = null;
			boolean initItem = false;

			try {
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(new StringReader(xml));

				int eventType = parser.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						Log.d(TAG, "START_DOCUMENT");
						break;
					case XmlPullParser.START_TAG:
						Log.d(TAG, "START_TAG");
						if (parser.getName().equalsIgnoreCase("item")) {
							item = new Item();
							initItem = true;
						}
						// 속성이 존재하면 반드시 여기서 호출
						if (parser.getAttributeCount() > 0) {
							for (int i = 0; parser.getAttributeCount() > i; i++) {
								if (parser.getAttributeName(i)
										.equalsIgnoreCase("price")) {
									item.setItemPrice(Integer.parseInt(parser
											.getAttributeValue(i)));
								}else{
									item.setItemMaker(parser.getAttributeValue(i));
								}
							}
						}
						break;
					case XmlPullParser.TEXT:
						Log.d(TAG, "TEXT");
						if(initItem){
							item.setItemName(parser.getText());
						}
						break;
					case XmlPullParser.END_TAG:
						Log.d(TAG, "END_TAG");
						if(parser.getName().equalsIgnoreCase("item")){
							initItem = false;
							arLists.add(item);
						}
						break;
					case XmlPullParser.END_DOCUMENT:
						Log.d(TAG, "END_DOCUMENT");
						break;

					}
					eventType = parser.next();

				}
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return arLists;
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(PullParser.this, result);
			list.setAdapter(adapter);
			progressDlg.dismiss();
		}
	}
}
